﻿using System;
using System.Collections.Generic;
using System.Text;

namespace RuoTeng.Util
{  
    using Newtonsoft.Json.Linq;
    class ParseJson
    {

        /// <summary>
        /// 强制类型转换为以下类型 string，int uint等
        /// </summary>
        /// <param name="jValue"></param>
        /// <returns></returns>
        public static string ParseString(JValue jValue)
        {  
            return  (jValue!=null && jValue.Value!=null) ?  jValue.Value.ToString() : "";         
        }

        public static int  ParseInt(JValue jValue)
        {
            return ParseType.ParseInt(ParseString(jValue)); 
        }

        public static uint ParseUInt(JValue jValue)
        {
            return ParseType.ParseUInt(ParseString(jValue));
        }

        public static ulong ParseULong(JValue jValue)
        {
            return ParseType.ParseULong(ParseString(jValue));
        }
       /// <summary>
       /// 根据json路径获取json集合中相关对象
       /// 
       /// 例子:
       /// 
        /// {people:[{name:"dwh",age:22},{name:"12",age:22}],count:2}
        /// 取第一个people的name的path是 people.0.name
        /// 取数量是多少的path是 people.count
        /// ParseJObject("people.0.name",(JObject)people)
       /// </summary>
       /// <param name="jsonPath"></param>
       /// <param name="jObject"></param>
       /// <returns></returns>
        public static object ParseJObject(string jsonPath,JObject jObject)
        {   
            if(jObject==null)
            { 
                return null;
            }
            string[] paths=jsonPath.Split('.');
            object __JObject = null;
            object __TempJObject = jObject;
            foreach(string str in paths)
            {
               if (__TempJObject== null)
               {
                    __JObject = null;
                    break;
               }
               object _o =null;
               if(__TempJObject is JObject) 
               {
                   _o = ((JObject)__TempJObject)[str];
               }
               else if(__TempJObject is JArray)
               {
                   int index = ParseType.ParseInt(str);
                   if (index.ToString() == str)
                   {
                       _o = ((JArray)__TempJObject)[index];
                   }
                   else
                   {
                       _o = null;
                   }
               }
               if(_o==null)
               {
                 __JObject=null; break;
               }
               else
               {                
                  __TempJObject = __JObject = _o;             
               }     
            }
            return __JObject;
        }
    }
}
